package club.jdiy.admin.interceptor;

import club.jdiy.admin.SystemConfig;
import club.jdiy.core.AppContext;
import club.jdiy.core.base.domain.Ret;
import club.jdiy.utils.JsonUtils;
import club.jdiy.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    private final List<Integer> errorCodeList = Arrays.asList(404, 403, 500, 501);

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object arg2, ModelAndView view) {
        if (view != null && !view.isEmpty())
            view.getModelMap().put("_", "" + System.currentTimeMillis());
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
        if (errorCodeList.contains(response.getStatus()) && !"1".equals(request.getAttribute("isJumpToErrorPaged"))) {
            request.setAttribute("isJumpToErrorPaged", "1");
            String s = "/etc/error/" + response.getStatus();
            request.getRequestDispatcher(s).forward(request, response);
            return false;
        }
        //#######设置cookies变量以便freemarker用
        Map<String, String> cookies = new HashMap<>();
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                cookies.put(cookie.getName(), cookie.getValue());
            }
        }
        request.setAttribute("cookies", cookies);
        //#######设置cookies变量以便freemarker用
        return passMaintain();
    }


    private boolean passMaintain() throws Exception {
        SystemConfig sc = context.getConfig(SystemConfig.class);
        String p = context.getRequest().getRequestURI() + "";
        if (p.startsWith("http:") || p.startsWith("https:"))
            p = p.substring(p.indexOf("://") + 3).substring(p.indexOf("/"));
        if (p.startsWith("/mgmt/") || p.startsWith("/etc/yzm") || p.startsWith("/etc/error")) return true;
        boolean isMaintain = false;
        if (sc.isMaintainOn() && StringUtils.hasText(sc.getMaintainPaths())) {
            String[] sa = sc.getMaintainPaths().split("\n");
            for (String s : sa) {
                if (StringUtils.hasText(s)) {
                    if (p.startsWith(s.trim())) isMaintain = true;
                    break;
                }
            }
        }
        if (isMaintain) {
            context.getResponse().addHeader("content-type", "text/html;charset=utf-8");
            String maintainMsg = StringUtils.hasText(sc.getMaintainMsg()) ? sc.getMaintainMsg() : "系统维护中，请稍后访问";
            context.getResponse().getWriter().print(
                    "XMLHttpRequest".equals(context.getRequest().getHeader("X-Requested-With"))
                            || "application/x-www-form-urlencoded".equals(context.getRequest().getHeader("content-type"))
                            || "application/form-data".equals(context.getRequest().getHeader("content-type"))
                            ? JsonUtils.stringify(Ret.fail(maintainMsg))
                            : maintainMsg
            );
            return false;
        }
        return true;
    }

    @Resource
    private AppContext context;
}